package com.wsjzzcbq.config;

import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

/**
 * SentinelConfig
 *
 * @author wsjz
 * @date 2023/10/08
 */
@Component
public class SentinelConfig {

    @PostConstruct
    public void initSentinelConfig() {
        //限流
        List<FlowRule> rules = new ArrayList<>();
        FlowRule flowRule = new FlowRule();
        flowRule.setResource("user-name-resource");
        flowRule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        flowRule.setCount(2);
        rules.add(flowRule);

        FlowRule flowRule2 = new FlowRule();
        flowRule2.setResource("user-age-resource");
        flowRule2.setGrade(RuleConstant.FLOW_GRADE_QPS);
        flowRule2.setCount(2);
        rules.add(flowRule2);

        FlowRuleManager.loadRules(rules);

        //熔断
        List<DegradeRule> degradeRules = new ArrayList<>();
        DegradeRule degradeRule = new DegradeRule();
        degradeRule.setResource("user-addr-resource");
        degradeRule.setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_COUNT);
        // 60s内调用接口出现异常次数超过5的时候, 进行熔断
        degradeRule.setCount(5);
        //统计时长（单位为 ms），如 60*1000 代表分钟级
        degradeRule.setStatIntervalMs(60 * 1000);
        //熔断时长
        degradeRule.setTimeWindow(80);
        degradeRules.add(degradeRule);
        DegradeRuleManager.loadRules(degradeRules);
    }
}
